<?php

if (!function_exists('arraySort')) {
    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC 
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}

if (!function_exists('array_group_by')) {
    /**
     * 二维数组根据某个字段进行分组
     * @param $arr 原数组
     * @param $key 需要分组的键名
     * @return array
     */
    function array_group_by($arr, $key)
    {
        $grouped = [];
        foreach ($arr as $value) {
            $grouped[$value[$key]][] = $value;
        }
        // Recursively build a nested grouping if more parameters are supplied
        // Each grouped array value is grouped according to the next sequential key
        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('array_group_by', $parms);
            }
        }
        return $grouped;
    }
}

if (!function_exists('getDegree')) {
    //难度系数计算 平均分/满分
    function getDegree($num, $total)
    {
        return round($num / $total, 2);
    }
}

if (!function_exists('getAverage')) {
    //计算平均数
    function getAverage($num, $total)
    {
        return round($num / $total, 2);
    }
}


if (!function_exists('getMedian')) {
    //计算中位数
    function getMedian($array)
    {
        sort($array);
        $mid = floor((count($array) - 1) / 2);
        if (count($array) % 2) {
            $median = $array[$mid];
        } else {
            $median = ($array[$mid] + $array[$mid + 1]) / 2;
        }
        return $median;
    }
}


if (!function_exists('getMode')) {
    //获取众数
    function getMode($array)
    {
        $count = array_count_values($array);
        arsort($count);
        $mode = key($count);
        return $mode;
    }
}


if (!function_exists('getStandardDeviation')) {
    /**
     * 计算总体标准差
     * @param array $array [1,2,3,4,10,5]
     * @param int $scale 保留小数
     * @return false|float
     */
    function getStandardDeviation($array, $scale = 2)
    {

        $n = count($array);
        $avg = bcdiv(array_sum($array), $n, 5);
        $stdev = sqrt(bcdiv(array_sum(array_map(function ($item) use ($avg) {
            return pow(bcsub($item, $avg, 5), 2);
        }, $array)), $n, 5));
        return round($stdev, $scale);
    }
}


if (!function_exists('getBonus')) {
    //划分区间 [0,10]
    function getBonus($total = 300, $num = 7, $max = 15)
    {
        $data = [];
        $average = round($total / $max);
        if ($average < $num) {
            $num = $average;
        }
        $left = 0;
        for ($i = 1; $i <= $num; $i++) {
            $right = $max * $i;
            if ($i == 0) {
                $data[$i] = [$left, $max];
                $left = $right;
            } elseif ($i == $num) {
                $data[$i] = [$left, $total];
            } else {
                $data[$i] = [$left, $max * $i];
                $left = $right;
            }
        }
        return $data;
    }
}


if (!function_exists('getSection')) {

    //区间处理
    function getSection($total = 300, $num = 5, $min = 0, $max = 50)
    {

        $data = [];
        if ($min * $num > $total) {
            return [];
        }
        for ($i = 0; $i < $num; $i++) {
            $k = $i+1;
            $kmin = $min;
            $kmax = $min + $max;
            if ($kmax > $total || $k == $num) {
                $kmax = $total;
            }
            $k = [$kmin, $kmax];
            $data[$i] = $k;
            $min = $kmax;
        }
        return $data;
    }
}


if (!function_exists('getScoring')) {

    /**
     * 得分率=实际得分/满分分值*100%
     *
     * @param int $score 实际得分
     * @param int $fullScore 满分分值
     * @return float
     */
    function getScoring($score, $fullScore)
    {
        $scoring = ($score / $fullScore) * 100;
        return round($scoring, 2);
    }
}

if (!function_exists('getAverageScoring')) {

    /**
     * 平均得分率=平均分/满分分值*100%
     *
     * @param int $aveScore 平均分
     * @param int $fullScore 满分分值
     * @return float
     */
    function getAverageScoring($aveScore, $fullScore)
    {
        $averageScoring = ($aveScore / $fullScore) * 100;
        return round($averageScoring, 2);
    }
}

if (!function_exists('getRates')) {

    /**
     * 三率=相应的人数/参考总数
     *
     * @param int $num  相应的人数
     * @param int $totalNum 参考总数
     * @return float
     */
    function getRates($num, $totalNum)
    {
        return round($num / $totalNum, 2);
    }
}


if (!function_exists('getCompositeRate')) {
    /**
     * 综合率=平均得分率*50%+优秀率*25%+及格率*25%
     *
     * @param int $averageScoring  平均得分率
     * @param int $excellenceRate 优秀率
     * @param int $passRate 及格率
     * @return float
     */
    function getCompositeRate($averageScoring, $excellenceRate, $passRate)
    {
        $compositeRate = ($averageScoring * 0.5) + ($excellenceRate * 0.25) + ($passRate * 0.25);
        return round($compositeRate, 4);
    }
}


if (!function_exists('httpCurl')) {
	/**
	 * curl 请求
	 *
	 * @param string $url
	 * @param array $params
	 * @return void
	 */
	function httpCurl($url, $params, $method = 'GET', $header = array(), $multi = false)
	{
		date_default_timezone_set('PRC');
		$opts = array(
			CURLOPT_TIMEOUT => 30,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_COOKIESESSION => true,
			CURLOPT_FOLLOWLOCATION => 1,
			CURLOPT_COOKIE
			=> session_name() . '=' . session_id(),
		);

		/* 根据请求类型设置特定参数 */
		switch (strtoupper($method)) {
			case 'GET':
				// $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
				// 链接后拼接参数  &  非？
				$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
				break;
			case 'POST':                //判断是否传输文件
				$params = $multi ? $params : http_build_query($params);
				$opts[CURLOPT_URL] = $url;
				$opts[CURLOPT_POST] = 1;
				$opts[CURLOPT_POSTFIELDS] = $params;
				break;
			default:
				throw new Exception('不支持的请求方式！');
		}

		/* 初始化并执行curl请求 */
		$ch = curl_init();
		curl_setopt_array($ch, $opts);
		$data = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if ($error) throw new Exception('请求发生错误：' . $error);
		return $data;
	}
}
